using UnityEngine;

public class SkillObject_TimeEcho : SkillObject_Base
{
    protected Skill_TimeEcho echoManager;
    private SpriteRenderer spriteRenderer;
    private SkillObject_Health echoHealth;
    private PlayerSkillManager skillManager;
    private Entity_StatHandler playerStatHandler;
    private TrailRenderer trail;
    [Header("----- Destory Details -----")]
    [SerializeField] private GameObject destoryVFX;

    [Header("----- Heal Wisp Details -----")]
    [SerializeField] private float healWispMoveSpeed = 15f;


    protected float duration;
    private int attackCount;
    private bool isHealWeap;
    private bool canMoveToPlayer;
    protected override void Update()
    {
        base.Update();
        animator.SetFloat("yVelocity", rb.velocity.y);

        if (canMoveToPlayer)
            MoveToPlayer();
    }

    public void SetUpTimeEcho(Skill_TimeEcho echoManager)
    {
        this.echoManager = echoManager;
        skillManager = echoManager.skillManager;
        spriteRenderer = GetComponentInChildren<SpriteRenderer>();
        echoHealth = GetComponent<SkillObject_Health>();
        trail = GetComponentInChildren<TrailRenderer>();
        playerStatHandler = echoManager.player.GetComponent<Entity_StatHandler>();
        duration = echoManager.GetLifeDuration;

        player = echoManager.player;
        

        damageScaleData = echoManager.damageScaleData;

        isHealWeap = echoManager.CanHealWisp();
        trail.gameObject.SetActive(false);
        attackCount = echoManager.GetAttackCount();

        //当攻击次数大于0时为true执行
        animator.SetBool("Attack", attackCount > 0);

        //处理分身翻转
        HandleFlip();

        Invoke(nameof(HandleDestory), duration);
    }

    private void MoveToPlayer()
    {
        if (player == null)
            return;
            
        if (Vector2.Distance(transform.position, player.transform.position) < .3f)
        {
            HandlePlayerTouchWisp();
            Destroy(gameObject);
            return;
        }

        transform.position = Vector2.MoveTowards(transform.position, player.transform.position, healWispMoveSpeed * Time.deltaTime);
    }
    //处理恢复健康值
    public void HandlePlayerTouchWisp()
    {
        float recoverHealth = echoHealth.lastTakeDamage * echoManager.GetDamagePercentHeal();
        echoHealth.IncreaseHealth(recoverHealth);

        //处理减少技能冷却
        float cooldownReduction = echoManager.GetCooldownReducedInSeconds();
        skillManager.ReduceAllSkillCooldown(cooldownReduction);

        if (echoManager.CanRemoveNegativeEffects())
            playerStatHandler.RemoveAllNegativeEffects();

    }

    //处理翻转
    public void HandleFlip()
    {
        Transform target = GetClosestTargetEnemy();
        if (target == null)
            transform.Rotate(0, player.facingDir == 1 ? 0 : 180, 0);
        if (target != null && target.transform.position.x < transform.position.x)
                transform.Rotate(0, 180, 0);

    }
    //处理攻击
    public void HandleAttack()
    {
        DamageEnemiesInRedius(targetCheck, 1f);
        Transform target = lastAttackTarget;
        if (target == null)
            return;
        if (echoManager.CanMutiply() == false)
            return;

        bool canDuplicate = Random.value < echoManager.GetMultiplyProbability();

        if (canDuplicate)
        {
            float xOffset = (target.position.x - transform.position.x) > 0 ? 1 : -1;
            echoManager.CreateTimeEcho(target.position + new Vector3(xOffset, 0, 0));
            echoManager.SetCurrentMutiply();
        }
    }
    //处理死亡
    public void HandleDestory()
    {
        //当执行死亡逻辑时，取消自动销毁，避免多次执行HandleDestory()函数
        CancelInvoke(nameof(HandleDestory));
        GameObject prefab = PoolManager.Instance.Release(destoryVFX, (prefab) =>
        {
            prefab.transform.position = transform.position;
            prefab.transform.rotation = Quaternion.identity;
        });
        
        if (isHealWeap)
        {
            spriteRenderer.enabled = false;
            canMoveToPlayer = true;
            rb.simulated = false;
            trail.gameObject.SetActive(true);        
        }
        else
            Destroy(gameObject);
    }
    public int GetAttackCount() => attackCount;
}
